<template>
  <el-dialog v-model="dialogVisible" title="计划单货物" width="90%" :before-close="handleClose">
    <el-form :inline="true" :model="formInline" class="demo-form-inline grids columnsLine4">
      <el-form-item label="货物编码">
        <el-input v-model="formInline.cargoSn" placeholder="请输入货物编码" clearable />
      </el-form-item>
      <el-form-item label="货物名称">
        <el-input v-model="formInline.cargoName" placeholder="请输入货物名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="init">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData.rows" @select="handleSelectionChange" ref="tableRef">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" />
      <el-table-column prop="batchNumber" label="批次号" align="center" min-width="150" />
      <el-table-column prop="cargoSn" label="货物编码" align="center" min-width="150" />
      <el-table-column prop="cargoName" label="货物名称" />
      <el-table-column prop="planNum" label="计划入库数量" />
      <el-table-column prop="realNum" label="实际入库数量" />
      <el-table-column prop="cargoUnit" label="单位">
        <template #default="scope">
          <selectUnit v-model="scope.row.cargoUnit" readonly="1"></selectUnit>
        </template>
      </el-table-column>
      <el-table-column prop="cargoWeight" label="重量（KG）" />
      <el-table-column prop="cargoVolume" label="体积(m³)" />
      <el-table-column prop="cargoSpec" label="规格" />
      <el-table-column prop="remark" label="备注" min-width="200" align="center" />
    </el-table>
    <Pagination v-if="tableData['total']" :total="tableData['total']" v-model:page="formInline.pageNum" v-model:limit="formInline.pageSize" @pagination="getData" />

    <el-card class="box-card" shadow="never">
      <template #header>
        选中的
      </template>
      <el-table :data="selectArr">
        <el-table-column type="index" width="50" />
        <el-table-column prop="batchNumber" label="批次号" align="center" min-width="150" />
        <el-table-column prop="cargoSn" label="货物编码" align="center" min-width="150" />
        <el-table-column prop="cargoName" label="货物名称" />
        <el-table-column prop="address" label="单价" min-width="150" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitPrice" placeholder="单价" min-width="150" align="center" />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="数量" min-width="150" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.num" placeholder="数量" />
          </template>
        </el-table-column>
        <el-table-column label="金额">
          <template #default="scope">
            {{(scope.row.num*scope.row.unitPrice)||0}}
          </template>
        </el-table-column>
        <el-table-column label="货物属性" min-width="150" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.type" placeholder="请选择">
              <el-option label="良品" :value="1" />
              <el-option label="不良品" :value="2" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="托盘码" min-width="150" align="center">
          <template #default="scope">
            <selectTray v-model="scope.row.trayId"></selectTray>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="scope">
            <selectUnit v-model="scope.row.cargoUnit" readonly="1"></selectUnit>
          </template>
        </el-table-column>
        <el-table-column label="工厂" min-width="150" align="center">
          <template #default="scope">
            <selectFactory v-model="scope.row.factoryId"></selectFactory>
          </template>
        </el-table-column>
        <el-table-column min-width="150" align="center" label="仓库">
          <template #default="scope">
            <selectStores v-model="scope.row.storeId" :factoryId="scope.row.factoryId"></selectStores>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="库区" min-width="150" align="center">
          <template #default="scope">
            <selectStoreRegion v-model="scope.row.storeRegionId" :factoryId="scope.row.factoryId" :storeId="scope.row.storeId"></selectStoreRegion>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="库位" min-width="150" align="center">
          <template #default="scope">
            <selectStoreLocation v-model="scope.row.storeRegionLocationId" :factoryId="scope.row.factoryId" :storeId="scope.row.storeId" :storeRegionId="scope.row.storeRegionId"></selectStoreLocation>
          </template>
        </el-table-column>
        <el-table-column prop="cargoSpec" label="规格" min-width="200" align="center" />
        <el-table-column prop="address" label="货物有效期" min-width="200" align="center">
          <template #default="scope">
            <DatePicker v-model="scope.row.validityDate"></DatePicker>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" text @click="selectArr.splice(scope.$index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认 新 增
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["fatherMethods"]);
let dialogVisible = ref(false);
let formInline = ref({
  pageNum: 1,
  pageSize: 10,
  inPlanId: "",
  cargoSn: "",
  cargoName: "",
});
let inPlanId = "";
let inWarehousId: ""; //入库单id
let tableData = ref({});
let selectArr = ref([]); //选中的数组
let addForm = {
  batchNumber: "",
  cargoId: "",
  cargoSn: "",
  cargoName: "",
  unitPrice: "",
  num: "",
  type: "",
  cargoUnit: "",
  factoryId: "",
  storeId: "",
  storeRegionId: "",
  storeRegionLocationId: "",
  trayId: "",
  cargoSpec: "",
  validityDate: "",
  inWarehousId: "",
};
let loading = ref(false);
let open = async (id, id2) => {
  inPlanId = id;
  inWarehousId = id2;
  await getData();
  dialogVisible.value = true;
};
let getData = async () => {
  formInline.value.inPlanId = inPlanId;
  tableData.value = await proxy.$apis.inPlanDetailList(formInline.value);
  //默认选中
  selectArr.value.forEach((row) => {
    let index = proxy.$utils.findIndexByField(
      tableData.value.rows,
      "id",
      row.id
    );
    if (index >= 0) {
      nextTick(() => {
        proxy.$refs.tableRef.toggleRowSelection(
          tableData.value.rows[index],
          true
        );
      });
    }
  });
};
let handleClose = () => {
  init();
  selectArr.value = [];
  emit("fatherMethods");
  dialogVisible.value = false;
};
let init = () => {
  formInline.value = {
    pageNum: 1,
    pageSize: 10,
    inPlanId: "",
    cargoSn: "",
    cargoName: "",
  };
  addForm = {
    batchNumber: "",
    cargoId: "",
    cargoSn: "",
    cargoName: "",
    unitPrice: "",
    num: "",
    type: "",
    cargoUnit: "",
    factoryId: "",
    storeId: "",
    storeRegionId: "",
    storeRegionLocationId: "",
    trayId: "",
    cargoSpec: "",
    validityDate: "",
    inWarehousId: "",
  };
  getData();
};
let search = () => {
  formInline.value.pageNum = 1;
  getData();
};
const handleSelectionChange = (selection, row) => {
  //新增
  if (proxy.$utils.isFieldEqual(selection, "id", row.id)) {
    selectArr.value.push({ ...row });
  } else {
    let index = proxy.$utils.findIndexByField(selection, "id", row.id);
    selectArr.value.splice(index, 1);
  }
};
let save = async () => {
  try {
    loading.value = true;
    let { data } = await proxy.$apis.inWarehousDetailQuery();
    console.log("全部列表", data);
    let array = proxy.$utils.deepcopy(selectArr.value);
    if (array.length == 0) return proxy.$utils.showToast(`请选择货物`, 0);
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      let str = `第${index + 1}行${element.cargoName}`;
      if (!element.num)
        return proxy.$utils.showToast(`${str}的数量不可为空`, 0);
      if (!element.trayId)
        return proxy.$utils.showToast(`${str}的托盘码不可为空`, 0);
      if (!element.unitPrice)
        return proxy.$utils.showToast(`${str}的单价不可为空`, 0);
      if (!element.type)
        return proxy.$utils.showToast(`${str}的货物属性不可为空`, 0);
      if (!element.factoryId)
        return proxy.$utils.showToast(`${str}的工厂不可为空`, 0);
      if (!element.storeId)
        return proxy.$utils.showToast(`${str}的仓库不可为空`, 0);
      if (!element.storeRegionId)
        return proxy.$utils.showToast(`${str}的库区不可为空`, 0);
      if (!element.storeRegionLocationId)
        return proxy.$utils.showToast(`${str}的库位不可为空`, 0);
      //如果之前有新增过
      if (data.length) {
        let msg = checkTrayId(data, element);
        if (msg) return proxy.$utils.showToast(msg, 0);
      }
      let query = proxy.$utils.formatFunction(element, { ...addForm });
      query.inWarehousId = inWarehousId;
      await proxy.$apis.inWarehousDetailAdd(query);
    }
    proxy.$utils.showToast("新增成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let checkTrayId = (data, element) => {
  let current = proxy.$utils.findIndexByField(data, "trayId", element.trayId);
  if (current == -1) return "";
  let obj = data[current];
  if (obj.cargoId == element.cargoId) return "";
  return `该托盘已装货物${obj.cargoName},请更换托盘`;
};

defineExpose({ open });
</script>

<style lang="scss" scoped>
.box-card {
  margin-top: 50px;
}
</style>
